import logging
import numpy as np
from qtorch.core.qstrategy import QStrategy

class SimpleMACDStrategy(QStrategy):
    """
    MACD策略 - 使用新的QStrategy API实现
    
    参数：
        fast_period: 快线EMA周期
        slow_period: 慢线EMA周期
        signal_period: 信号线周期
    """
    
    def __init__(self, fast_period=12, slow_period=26, signal_period=9):
        super().__init__()
        self.fast_period = fast_period
        self.slow_period = slow_period
        self.signal_period = signal_period
        self.previous_histogram = 0
        
    def initialize(self):
        """策略初始化"""
        logging.info(f"初始化MACD策略: 快线={self.fast_period}, 慢线={self.slow_period}, 信号线={self.signal_period}")
        
    def next(self):
        """
        处理当前数据点，生成交易信号
        
        返回:
            int: 1(买入)、0(持有)、-1(卖出)
        """
        # 计算MACD指标
        macd_result = self.MACD(self.fast_period, self.slow_period, self.signal_period)
        
        # 如果数据不足，等待
        if macd_result is None:
            return 0
            
        # 获取当前柱状图值
        current_histogram = macd_result['histogram']
        
        # MACD柱状图由负变正，买入信号
        if self.previous_histogram < 0 and current_histogram > 0 and self.position <= 0:
            self.previous_histogram = current_histogram
            return 1  # 买入信号
            
        # MACD柱状图由正变负，卖出信号
        elif self.previous_histogram > 0 and current_histogram < 0 and self.position >= 0:
            self.previous_histogram = current_histogram
            return -1  # 卖出信号
            
        # 更新前一个柱状图值
        self.previous_histogram = current_histogram
        
        # 其他情况，持仓不变
        return 0